package org.finir.fakturisanje.business.eao;

import java.util.List;

import org.finir.fakturisanje.business.core.HibernateGenerickiEAOImpl;
import org.finir.fakturisanje.persistence.Faktura;
import org.finir.fakturisanje.persistence.Preduzece;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.transaction.annotation.Transactional;

@Transactional
public class FakturaEAOImpl extends HibernateGenerickiEAOImpl implements
		FakturaEAO {

	/**
	 * 
	 */
	private static final long serialVersionUID = -4922325818890175135L;

	public FakturaEAOImpl() {
		super();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.finir.fakturisanje.business.service.FakturaFacade#vratiSveFakture
	 * (java.lang.Integer, org.finir.fakturisanje.persistence.Preduzece)
	 */
	@SuppressWarnings("unchecked")
	public List<Faktura> vratiSveFakture(Integer year, Preduzece preduzece) {

		String hql = "from FakturaBean f where extract(year from f.datum)=? and f.preduzece=?";

		Session session = getSessionFactory().getCurrentSession();
		Query createQuery = session.createQuery(hql);
		createQuery.setEntity(1, preduzece);
		createQuery.setInteger(0, year);
		return createQuery.list();

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.finir.fakturisanje.business.service.FakturaFacade#getBrojFakture(
	 * java.lang.Integer, org.finir.fakturisanje.persistence.Preduzece)
	 */
	public Integer getBrojFakture(Integer year, Preduzece preduzece) {
		if (preduzece != null && year != null) {
			String hql = "select max(f.brojFakture) from FakturaBean f where extract(year from f.datum)=? and f.preduzece=?";
			Session session = getSessionFactory().getCurrentSession();
			Query createQuery = session.createQuery(hql);
			createQuery.setEntity(1, preduzece);
			createQuery.setInteger(0, year);

			Integer ret = (Integer) createQuery.uniqueResult();

			if (ret == null) {
				return 1;
			} else {
				return (ret + 1);
			}
		}
		return null;

	}

}
